package com.jintu.portal.config;

import com.alibaba.fastjson.JSONObject;
import com.jintu.portal.pojo.entity.mysql.SysConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author very
 */
@Slf4j
@Component
public class SysConfigurer {

    private static final ConcurrentHashMap<String, String> SYS_CONFIG = new ConcurrentHashMap<>();

    public String getString(String key, String defaultVal) {
        String val = SYS_CONFIG.get(key);
        try {
            return StringUtils.isBlank(val) ? defaultVal : val;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return defaultVal;
        }
    }

    public Integer getInt(String key, Integer defaultVal) {
        String val = SYS_CONFIG.get(key);
        try {
            return StringUtils.isBlank(val) ? defaultVal : Integer.parseInt(val);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return defaultVal;
        }
    }

    public Boolean getBool(String key, Boolean defaultVal) {
        String val = SYS_CONFIG.get(key);
        try {
            return StringUtils.isBlank(val) ? defaultVal : Boolean.parseBoolean(val);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return defaultVal;
        }
    }

    public void updateProps(List<SysConfig> sysConfigs) {
        if (sysConfigs != null) {
            for (SysConfig sysConfig : sysConfigs) {
                SYS_CONFIG.put(sysConfig.getPropName(), sysConfig.getPropValue());
            }
        }
        log.info("系统配置参数更新为: {}", JSONObject.toJSONString(sysConfigs));
    }
}
